package main

import (
	"fmt"
	"github.com/wonderivan/logger"
	"github.com/xtaci/kcp-go"
	"sync"
)

var wg sync.WaitGroup

func createClient(index int) {
	defer wg.Done()
	kcpConn, err := kcp.DialWithOptions("192.168.1.57:9000", nil, 10, 3)
	if err != nil {
		panic(err)
	}
	err = kcpConn.SetReadBuffer(16 * 1024 * 1024)
	if err != nil {
		panic(err)
	}
	err = kcpConn.SetWriteBuffer(16 * 1024 * 1024)
	if err != nil {
		panic(err)
	}
	kcpConn.SetNoDelay(1, 10, 2, 1)
	kcpConn.SetStreamMode(true)
	kcpConn.SetWindowSize(1024, 1024)
	kcpConn.SetMtu(1400)
	kcpConn.SetACKNoDelay(false)
	msg := fmt.Sprintf("ping %d", index)
	for i := 0; i < 10000; i++ {
		_, err = kcpConn.Write([]byte(msg))
	}
	logger.Debug("client id=%d send ping", index)
	go receivedMsg(kcpConn, index)
}

func receivedMsg(kcpConn *kcp.UDPSession, index int) {
	b := make([]byte, 65535)
	if n, e := kcpConn.Read(b); e == nil {
		logger.Debug("receivedMsg index=%d msg=%s", index, string(b[:n]))
	} else {
		logger.Debug("receivedMsg error:%s", e)
	}
}

func main() {
	err := logger.SetLogger("log.json")
	if err != nil {
		panic(err)
	}
	maxConn := 100
	wg.Add(maxConn)
	for i := 0; i < maxConn; i++ {
		go createClient(i)
	}
	wg.Wait()
	select {}
}
